const app = getApp()
const db = wx.cloud.database()
const User = db.collection('user')
const Message = db.collection('message')
const _ = db.command

const time = require('../../utils/time.js')
 const util = require('../../utils/time.js')
Page({
 
  /**
   * 页面的初始数据
   */
  data: {
    InputBottom: 0,
    user: app.globalData.user,
    to: '', // 发送给谁
    toInfo: {}, //接受者信息
    queueWatch: '',// 消息监听
    content: '', // 发送内容
    message: [], // 聊天信息
    scrollLast: null,
    show:false, //是否显示弹出层
    margin: 0, //控制input框上浮
    type: 'text'// 发送类型
  },
  showPopup() {
    this.setData({ show: true });
    this.setData({ margin: 133 });
   },
   onClose() {
    this.setData({ show: false });
    // 延时300毫秒后再降低input框
    setTimeout(() => {
        this.setData({ margin: 0 });
     }, 300);
    
   },
   sendPhoto() {
    // wx.chooseMedia({
    //   count: 3,
    //   mediaType: 'image',
    //   sourceType: 'album',
    //   success(res) {
    //     console.log(res.tempFiles.tempFilePath)
    //     console.log(res)
    //   }
    // })
    var that = this
    wx.chooseImage({
      success: chooseResult => {
        var time = util.formatTime(new Date()) // 获取时间
        var randstring = Math.floor(Math.random() * 1000000).toString() + '.png'
        randstring = time + '-' + randstring
        console.log('time:',randstring)
          wx.cloud.uploadFile({
            // 指定上传到的云路径   
            cloudPath: 'message/images/' + randstring,  
            // 指定要上传的文件的小程序临时文件路径
            filePath: chooseResult.tempFilePaths[0],
            // 成功回调
            success: res => {
              console.log('上传成功:', res.fileID)
                that.data.content = res.fileID
                that.data.type = 'image'
                console.log('content:',that.data.content)
                that.handleSend()
                that.data.type = 'text'
                that.onClose()    // 为何不执行
            },
          })
        },
      })

   },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(option) {
    const user = app.globalData.user
    console.log('跳转_id:',option._id)
    this.setData({
      user: user,
      to:option._id
    })
    this.getToInfo()
    
  },
 
  /**
   * 获取接受者信息
   */
  getToInfo() {
    const { to } = this.data
    console.log('to:',to)
    const that = this
    // 设置navigationBarTitle   失败？
    User.where({
      _id: to
    }).get({
      success: function(res) {
        // console.log('name::',res.data[0].name)
        that.setData({ toInfo: res.data[0] })
     }
    })

  },
 
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const { to, user } = this.data
    // console.log('监听页面显示user:',user)
    // console.log('user:',user.name)
    // wx.setNavigationBarTitle({
    //   title: '好友：' + user.name,
    // })
    this.handleCreate(to, user._id)
    this.clear(to, user._id)
    this.handleWatch(true)
  },
  //消息自动到底部
  getScollBottom() {
    this.setData({ scrollLast: 'lastPosition' })
  },
  //创建聊天
  handleCreate(to, from, cb) {
    Message.where({ to, from }).get({
      success: ({ data }) => {
        if (data.length == 0) {
          Message.add({
            data: { to, from, message: [],no_read: Number },
            success: () => {
              (typeof cb == 'function') && cb()
            }
          })
        } else (typeof cb == 'function') && cb()
      }
    })
    
  },
  //添加信息
  handleAddMessage(to, from, message, cb) {
    Message.where({ to, from }).update({
      data: { message: _.push(message) },
      success: ({ data }) => {
        (typeof cb == 'function') && cb()
      }
    })
  },
  // 信息发送
  handleSend() {
    var time = util.formatTime(new Date()) // 获取时间
    time = time.split(' ')[1].substr(0,5)
    const { to, user, content,type} = this.data
    console.log('content:',content)
    if (!content) return
    const from = user._id
    const message = { from, content,type,time }
    // console.log('message:',message)
    const that = this
    this.handleAddMessage(to, from, message, () => {
      // 对方no_add加一
      that.add(to,from)
      console.log('添加成功')
      //接受者创建对话和添加信息
      that.handleCreate(from, to, () => {
        that.handleAddMessage(from, to, message, () => {
          that.setData({ content: '' })
        })
      })
    })
  },
  clear(to,from) {
    // no_read清零
    Message.where({
      from: from,
      to: to
    }).update({data: {no_read: 0}})
  },
  add(to,from) {
    let current = 0
    Message.where({
      from: to,
      to: from
    }).get({success:function(res) {
      current = res.data[0].no_read
    }})
    
    setTimeout(()=>{
      Message.where({
        from: to,
        to: from
      }).update({data: {no_read: current+1}})
    },500)
    // no_read加一
  

  },

  InputFocus({ detail: { height } }) {
    this.setData({ margin: height })
  },
  InputBlur(e) {
    this.setData({ margin: 0 })
  },
 
  /**
   * 监听消息变化
   */
  handleWatch: async function (watch) {
    let { queueWatch, to, user } = this.data
    const that = this
    if (watch && !queueWatch) { // 监听
      queueWatch = Message.where({ to, from: user._id })
        .watch({// 发起监听
          onChange: function ({ docs }) {
            
            const { message = [] } = docs[0] || {}
            // console.log("监听后：",message)
            that.setData({ message })
            that.getScollBottom()
          },
          onError: function (err) {
            console.error('the watch closed because of error', err)
          }
        })
      this.setData({ queueWatch })
    } else if (!watch && queueWatch) { // 取消监听
      await queueWatch.close()
      this.setData({ queueWatch: '' })
    }
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onHide: function () {
    this.handleWatch(false) // 取消监听
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
 
  },
 
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
 
  },
 
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
 
  }
})